<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin_Samples extends Admin_Controller {
	public function __construct()
	{
		parent::Admin_Controller();
		$this->config->load('cirpho');
		$this->load->helper(array('form', 'url'));
		$this->lang->load('cirpho');
		$this->lang->load('samples');
		$this->load->model('cip_samples_m');
		$this->load->model('cip_settings_m');
		$this->load->model('cip_servers_m');
		$this->template
			->append_metadata( css('cirpho.css', 'cirpho') )
			->append_metadata(js('cirpho.js', 'cirpho'))
			->set_partial('shortcuts', 'admin/partials/shortcuts');
		// Set the validation rules
		$this->load->library('form_validation');
		$this->validation_rules = array(
			array(
			'field' => 'userfile',
			'label' => 'lang:files.file_label',
			'rules' => 'callback__check_ext'
			)
		);
		$this->form_validation->set_rules($this->validation_rules);
		$this->_path = FCPATH . $this->config->item('files_folder');
		$this->_files_thums_folder = FCPATH . $this->config->item('files_thums_folder');
		$this->_command_folder = $this->config->item('command_folder');
		$this->_thumb_width = $this->config->item('thumb_width');
		$this->_thumb_height = $this->config->item('thumb_height');
		$this->_check_dir();
	}
	public function manage($gid)
	{
		if(isset($_POST['server']) && $_POST['server'] != "0"){
			$selectedServer = $this->cip_servers_m->get_by('id',$_POST['server']);
		}else{
			$selectedServer = null;
		}
		$this->pyrocache->delete_all('modules_m');
		// Create pagination links
		//$total_rows = $this->cip_samples_m->count_all();
		$total_rows = $this->cip_samples_m->count_by('group_id', $gid);
		$pagination = create_pagination('admin/cirpho/samples/manage/'.$gid, $total_rows, NULL, 6);
		// Using this data, get the relevant results
		$samples = $this->cip_samples_m->where('group_id', $gid)->order_by('id')->limit($pagination['limit'])->get_all();
		$servers = $this->cip_servers_m->order_by('name', 'ASC')->get_all();
		$this->template
			->title($this->module_details['name'], lang('cirpho_sample_list_title'))
			->set('samples', $samples)
			->set('pagination', $pagination)
			->set('imagePath', $this->_path)
			->set('imageThumsPath', $this->_files_thums_folder)
			->set('groupId', $gid)
			->set('thumbWidth', $this->_thumb_width)
			->set('thumbHeight', $this->_thumb_height)
			->set('sampleFolderPath', $this->config->item('files_folder'))
			->set('thumFolderPath', $this->config->item('files_thums_folder'))
			->set('servers', $servers)
			->set('selectedServer', $selectedServer)
			->append_metadata( css('jquery.fileupload-ui.css', 'cirpho') )
			->append_metadata( css('files.css', 'cirpho') )
			->append_metadata( js('jquery/jquery.cooki.js') )
			->append_metadata( js('jquery.fileupload.js', 'cirpho') )
			->append_metadata( js('jquery.fileupload-ui.js', 'cirpho') )
			->append_metadata( js('jquery.ba-hashchange.min.js', 'cirpho') )
			->append_metadata( js('functions.js', 'cirpho') )
			->build('admin/samples/index', $this->data);
	}
	
	/**
	 * Upload
	 *
	 * Upload a file to the destination folder
	 *
	 * @params int	The folder id
	 */
	public function upload($groupId = '')
	{
		$this->data->folders = $this->_folders;
		if ($this->form_validation->run())
		{
			// Setup upload config
			$this->load->library('upload', array(
				'upload_path'	=> $this->_path,
				'allowed_types'	=> $this->_ext,
				'file_name'		=> $this->_filename
			));
			// File upload error
			if ( ! $this->upload->do_upload('userfile'))
			{
				$status		= 'error';
				$message	= $this->upload->display_errors();

				if ($this->input->is_ajax_request())
				{
					$data = array();
					$data['messages'][$status] = $message;
					$message = $this->load->view('admin/partials/notices', $data, TRUE);

					return $this->template->build_json(array(
						'status'	=> $status,
						'message'	=> $message
					));
				}

				$this->data->messages[$status] = $message;
			}

			// File upload success
			else
			{
				$file = $this->upload->data();
				$data = array(
					'folder_id'		=> (int) $this->input->post('folder_id'),
					'user_id'		=> (int) $this->user->id,
					'type'			=> $this->_type,
					'name'			=> $this->input->post('name'),
					'description'	=> $this->input->post('description') ? $this->input->post('description') : '',
					'filename'		=> $file['file_name'],
					'extension'		=> $file['file_ext'],
					'mimetype'		=> $file['file_type'],
					'filesize'		=> $file['file_size'],
					'width'			=> (int) $file['image_width'],
					'height'		=> (int) $file['image_height'],
					'date_added'	=> now()
				);
				$sampleData = array(
					'image' => $file['file_name'],
					'group_id' => $groupId,
					'built' => 0
				);
				// Insert success
				//if ($id = $this->file_m->insert($data))
				if ($id = $this->cip_samples_m->insert($sampleData))
				{
					$status		= 'success';
					$message	= lang('files.create_success');
				}
				// Insert error
				else
				{
					$status		= 'error';
					$message	= lang('files.create_error');
				}

				if ($this->input->is_ajax_request())
				{
					$data = array();
					$data['messages'][$status] = $message;
					$message = $this->load->view('admin/partials/notices', $data, TRUE);
					return $this->template->build_json(array(
						'status'	=> $status,
						'message'	=> $message,
						'file'		=> array(
							'name'	=> $file['file_name'],
							'type'	=> $file['file_type'],
							'size'	=> $file['file_size'],
							'thumb'	=> base_url() . 'files/thumb/' . $id . '/80'
						)
					));
				}

				if ($status === 'success')
				{
					$this->session->set_flashdata($status, $message);
					redirect('admin/cirpho/samples');
				}
			}
		}
		elseif (validation_errors())
		{
			// if request is ajax return json data, otherwise do normal stuff
			if ($this->input->is_ajax_request())
			{
				$message = $this->load->view('admin/partials/notices', array(), TRUE);

				return $this->template->build_json(array(
					'status'	=> 'error',
					'message'	=> $message
				));
			}
		}

		if ($this->input->is_ajax_request())
		{
			// todo: debug errors here
			$status		= 'error';
			$message	= 'unknown';

			$data = array();
			$data['messages'][$status] = $message;
			$message = $this->load->view('admin/partials/notices', $data, TRUE);

			return $this->template->build_json(array(
				'status'	=> $status,
				'message'	=> $message
			));
		}

		// Loop through each validation rule
		foreach ($this->_validation_rules as $rule)
		{
			if ($rule['field'] == 'folder_id') 
			{
				$this->data->file->{$rule['field']} = set_value($rule['field'], $folder_id);
			}
			else
			{
				$this->data->file->{$rule['field']} = set_value($rule['field']);
			}
			
		}

		$this->template
			->title()
			->build('admin/samples/upload', $this->data);
	}
	
	public function delete($gid = 0, $id= 0)
	{	
		if(isset($_POST['rebuild'])){
			$samples = $this->cip_samples_m->where('group_id', $gid)->get_all();
			$max_width = $this->cip_settings_m->get('max_width');
			if($samples){
				foreach ($samples as $sample){
					if(!$sample->built){
						system("/usr/bin/convert ".$this->_path.$sample->image." -resize ".$max_width->value." -type Grayscale -depth 8 ".$this->_path.$sample->image.".pgm");
						//echo $this->_command_folder."sift <".$this->_path.$sample->image.".pgm >".$this->_path.$sample->image.".key 2>/tmp/fasjegjegioajseig.tmp";
						//die();
						system($this->_command_folder."sift <".$this->_path.$sample->image.".pgm >".$this->_path.$sample->image.".key 2>/tmp/fasjegjegio123.tmp");
					}
				}
			}
			$this->session->set_flashdata('success', lang('cirpho_samples_rebuild_success'));
			redirect('admin/cirpho/samples/manage/'.$gid);
		}
		$id_array = (!empty($id)) ? array($id) : $this->input->post('action_to');
		
		// Delete multiple
		if(!empty($id_array))
		{
			$deleted = 0;
			$to_delete = 0;
			foreach ($id_array as $id) 
			{
				$imgTemp = $this->cip_samples_m->get($id);
				if($imgTemp){
					unlink($this->_path.$imgTemp->image);
				}
				if($this->cip_samples_m->delete($id))
				{
					$deleted++;
				}
				else
				{
					$this->session->set_flashdata('error', sprintf($this->lang->line('cirpho_sample_mass_delete_error'), $id));
				}
				$to_delete++;
			}
			
			if( $deleted > 0 )
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('cirpho_sample_mass_delete_success'), $deleted, $to_delete));
			}
		}		
		else
		{
			$this->session->set_flashdata('error', $this->lang->line('cirpho_owner_no_select_error'));
		}
		
		redirect('admin/cirpho/samples/manage/'.$gid);
	}
	
	/**
	 * Validate our upload directory.
	 */
	private function _check_dir()
	{
		if (is_dir($this->_path) && is_really_writable($this->_path))
		{
			return TRUE;
		}
		elseif ( ! is_dir($this->_path))
		{
			if ( ! @mkdir($this->_path, 0777, TRUE))
			{
				$this->data->messages['notice'] = lang('file_folders.mkdir_error');
				return FALSE;
			}
			else
			{
				// create a catch all html file for safety
				$uph = fopen($this->_path . 'index.html', 'w');
				fclose($uph);
			}
		}
		else
		{
			if ( ! chmod($this->_path, 0777))
			{
				$this->session->messages['notice'] = lang('file_folders.chmod_error');
				return FALSE;
			}
		}
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Validate upload file name and extension and remove special characters.
	 */
	function _check_ext()
	{
		if ( ! empty($_FILES['userfile']['name']))
		{
			$ext		= pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
			$allowed	= $this->config->item('cirpho_allowed_file_ext');
			foreach ($allowed as $type => $ext_arr)
			{				
				if (in_array(strtolower($ext), $ext_arr))
				{
					$this->_type		= $type;
					$this->_ext			= implode('|', $ext_arr);
					$this->_filename	= trim(url_title($_FILES['userfile']['name'], 'dash', TRUE), '-');

					break;
				}
			}

			if ( ! $this->_ext)
			{
				$this->form_validation->set_message('_check_ext', lang('files.invalid_extension'));
				return FALSE;
			}
		}		
		elseif ($this->method === 'upload')
		{
			$this->form_validation->set_message('_check_ext', lang('files.upload_error'));
			return FALSE;
		}

		return TRUE;
	}
}